//
//  RaknetHelper.h
//  boxer
//
//  Created by Wu Wang on 11-12-14.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#ifndef boxer_RaknetHelper_h
#define boxer_RaknetHelper_h

#include "GameDefine.h"

#ifdef GAME_USERAKNET

#include "RakPeerInterface.h"
#include "BitStream.h"
#include "MessageIdentifiers.h"

#include "IGCHelper.h"



class CClientDelegate
{
public:
    virtual void connectServerSuccessed() {}
    virtual void opponentFound(const BoxerInfo &info) {}
    virtual void receiveServerInfo(const GameInfo &info) {}
	//virtual void receiveCommand(const ClientPacket &packet) {}
    virtual void connectServerFailed() {}
    virtual void connectLost() {}
	
};

class CRaknetHelper
{
    
public:
    
	~CRaknetHelper();
    
    static CRaknetHelper *GetInstance();
	RakNet::RakPeerInterface *GetRakPeer()    {return m_pRakPeer;}
	RakNet::RakNetGUID        GetServerGUID() {return m_serverGuid;}
	bool                      IsHost()        {return m_bHost;}

	void DeallocatePacket(RakNet::Packet *pPacket) {m_pRakPeer->DeallocatePacket(pPacket);}
	RakNet::Packet *ReceivePacket()                {return m_pRakPeer->Receive();}

	bool ConnectServer();
	bool ConnectRandomRoom();
	bool SendClientCommand(const ClientPacket &packet);
	bool SendServerInfo(const GameInfo &info);

    
	void DelayTest();
    bool BeginReceiveThread();
	bool StopReceiveThread();
    
private:
    CRaknetHelper();
    void ReceiveData();
    static void *ThreadReceiveData(void *arg);
    
private:
    RakNet::RakPeerInterface *m_pRakPeer;
    RakNet::RakNetGUID        m_serverGuid;
    CClientDelegate           *m_pClientDelegate;
    char                      m_userID[ID_MAX_LENGTH];
    bool                      m_bHost;
    bool                      m_bConnected;
    long                      m_delay;
    
    static pthread_t          m_pid;
    
};


class CAutoMutex
{
public:
	CAutoMutex();
	~CAutoMutex();
    
    static void Init();
    static void Destroy();
private:
	static pthread_mutex_t m_hMutex;
};

#endif

#endif
